package top.lyc829.zzl_android.ui.message.replay;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.core.util.TimeUtils;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.listener.OnItemSwipeListener;
import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.gson.Gson;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xutil.data.DateUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import okhttp3.Response;
import top.lyc829.zzl_android.R;
import top.lyc829.zzl_android.databinding.ActivityReplayBinding;
import top.lyc829.zzl_android.logic.bean.NoticeCommentBean;
import top.lyc829.zzl_android.logic.bean.NoticeSystemBean;
import top.lyc829.zzl_android.logic.bean.ResultBean;
import top.lyc829.zzl_android.logic.bean.SonCommentBean;
import top.lyc829.zzl_android.logic.network.Network;
import top.lyc829.zzl_android.logic.util.HttpUtil;
import top.lyc829.zzl_android.logic.util.PageInfo;
import top.lyc829.zzl_android.logic.util.ReplayType;
import top.lyc829.zzl_android.logic.util.Utils;
import top.lyc829.zzl_android.logic.util.gson.JsonUtilNew;
import top.lyc829.zzl_android.ui.base_detail.BaseDetailActivity;
import top.lyc829.zzl_android.ui.base_detail.SonCommentsAdapter;
import top.lyc829.zzl_android.ui.custom_view.InputTextMsgDialog;
import top.lyc829.zzl_android.ui.index.RecyclerViewAdapter;
import top.lyc829.zzl_android.ui.message.system.NoticeSystemActivity;
import top.lyc829.zzl_android.ui.profile.follow.user_detail.OtherUserDetailActivity;
import top.lyc829.zzl_android.ui.team.TeamRecyclerAdapter;
import top.lyc829.zzl_android.ui.thing.dynamic_detail.DynamicDetailActivity;
import top.lyc829.zzl_android.ui.thing.travel_detail.TravelDetailActivity;

public class ReplayActivity extends AppCompatActivity {

    ActivityReplayBinding binding;
    ReplayViewModel mViewModel;
    ReplayAdapter adapter;

    BottomSheetDialog dialog;
    SonCommentsAdapter sonAdapter;
    PageInfo pageInfo;
    InputTextMsgDialog inputTextMsgDialog;
    MaterialDialog loadingDialog;
    View sonCommentView;

    private int replayType = ReplayType.OTHER; // 回复类型，0 - 基地 1 - 评论
    private int commendedId = -1;    // 被评论的评论的id
    private int commentedUserId = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityReplayBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        pageInfo = new PageInfo();
        sonCommentView = LayoutInflater.from(this).inflate(R.layout.replay_comments, null);

        binding.mTitleBarReplay.setLeftClickListener(v -> finish());
        mViewModel = new ViewModelProvider.AndroidViewModelFactory(getApplication()).create(ReplayViewModel.class);

        // 实例化加载框
        loadingDialog = new MaterialDialog.Builder(this)
                .customView(R.layout.dialog_loading_layout, true)
                .cancelable(false)
                .build();

        initCommentDialog();

        initRecycler();
        observer();

        clickListener();


    }

    private void clickListener() {
        adapter.setOnItemClickListener((adapter1, view, position) -> {
            NoticeCommentBean comment = adapter.getItem(position);
            Intent intent;

            if (comment.getSourceType().equals(ReplayType.BASE)) {
                intent = new Intent(ReplayActivity.this, BaseDetailActivity.class);
                startActivity(intent);
            } else if (comment.getSourceType().equals(ReplayType.DYNAMIC)) {
                intent = new Intent(ReplayActivity.this, DynamicDetailActivity.class);
                intent.putExtra("id", adapter.getItem(position).getSourceId());
                intent.putExtra("is_comment", true);
                startActivity(intent);
            } else if (comment.getSourceType().equals(ReplayType.COMMENT)) {
                goCommentDialog(comment);
            } else if (comment.getSourceType().equals(ReplayType.TRAVEL)) {
                intent = new Intent(ReplayActivity.this, TravelDetailActivity.class);
                intent.putExtra("travel_id", adapter.getItem(position).getSourceId());
                intent.putExtra("is_comment", true);
                startActivity(intent);
            }

        });


        adapter.addChildClickViewIds(R.id.notice_comment_item_avatar);
        adapter.setOnItemChildClickListener((adapter1, view, position) -> {
            if (view.getId() == R.id.notice_comment_item_avatar) {
                Intent intent = new Intent(ReplayActivity.this, OtherUserDetailActivity.class);
                intent.putExtra("id", adapter.getItem(position).getUserId());
                startActivity(intent);
            }
        });

    }

    private void goCommentDialog(NoticeCommentBean comment) {

        mViewModel.getSuperCommentLiveData().setValue(null);
        mViewModel.getSonCommentsLiveData().setValue(null);
        pageInfo.reset();

        Utils.Sout(comment.toString());

        mViewModel.loadSuperComment(comment.getSourceId(), Utils.getUserId());
        mViewModel.loadSonComments(comment.getSourceId(), pageInfo.getPage());

        if (dialog == null) {
            dialog = new BottomSheetDialog(this);
            RecyclerView recyclerView = sonCommentView.findViewById(R.id.replay_recyclerview);

            LinearLayoutManager manager = new LinearLayoutManager(this);
            manager.setOrientation(RecyclerView.VERTICAL);
            recyclerView.setLayoutManager(manager);
            sonAdapter = new SonCommentsAdapter();
            recyclerView.setAdapter(sonAdapter);
            sonAdapter.setList(null);

            dialog.setContentView(sonCommentView);
            dialog.setCancelable(true);
            dialog.setCanceledOnTouchOutside(true);

            // 底部评论框监听器
            sonCommentView.findViewById(R.id.replay_bottom_comment).setOnClickListener(v -> {

                if (mViewModel.getSuperCommentLiveData().getValue() != null) {
                    showCommentDialog();
                    replayType = ReplayType.COMMENT;
                    commendedId = mViewModel.getSuperCommentLiveData().getValue().getCommentId();
                    commentedUserId = mViewModel.getSuperCommentLiveData().getValue().getUseId();
                }
            });

            sonAdapter.setOnItemClickListener((adapter1, view1, position) -> {
                if (sonAdapter.getData().size() > 0) {
                    showCommentDialog();
                    replayType = ReplayType.COMMENT;
                    commendedId = sonAdapter.getItem(position).getCommentId();
                    commendedId = comment.getSourceId();
                    commentedUserId = sonAdapter.getData().get(position).getUseId();
                }
            });

            sonAdapter.addChildClickViewIds(R.id.replay_item_like_btn,R.id.replay_item_avatar);
            sonAdapter.setOnItemChildClickListener((adapter1, view1, position) -> {
                if (view1.getId() == R.id.replay_item_like_btn) {
                    // 子评论点赞
                    if (!Utils.isLogin()) {
                        Utils.showToast("请先登录");
                        return;
                    }

                    //ShineButton shineButton = (ShineButton) view;
                    SonCommentBean sonComment = sonAdapter.getItem(position);
                    //未点赞，点赞请求
                    if (sonComment.getIsLike().equals(0)) {
                        Network.sendLike(Utils.getUserId(), ReplayType.COMMENT, sonAdapter.getItem(position).getCommentId(), new HttpUtil.MyCallback() {
                            @Override
                            public void success(Response res) throws IOException {
                                String resStr = res.body().string();
                                ResultBean<String> resultBean = JsonUtilNew.fromJsonObject(resStr, String.class);
                                if (resultBean.getCode().equals(200)) {
                                    runOnUiThread(() -> {
                                        sonAdapter.getItem(position).setIsLike(1);
                                        sonAdapter.getItem(position).setCommentLikes(sonAdapter.getItem(position).getCommentLikes() + 1);
                                        sonAdapter.notifyDataSetChanged();
                                    });
                                } else {
                                    failed(new IOException(resStr));
                                }
                            }

                            @Override
                            public void failed(IOException e) {
                                Utils.SoutErr(e.getMessage());
                            }
                        });
                    } else {
                        Network.sendUnLike(Utils.getUserId(), ReplayType.COMMENT, sonAdapter.getItem(position).getCommentId(), new HttpUtil.MyCallback() {
                            @Override
                            public void success(Response res) throws IOException {
                                String resStr = res.body().string();
                                ResultBean<String> resultBean = JsonUtilNew.fromJsonObject(resStr, String.class);
                                if (resultBean.getCode().equals(200)) {
                                    runOnUiThread(() -> {
                                        sonAdapter.getItem(position).setIsLike(0);
                                        sonAdapter.getItem(position).setCommentLikes(sonAdapter.getItem(position).getCommentLikes() - 1);
                                        sonAdapter.notifyDataSetChanged();
                                    });
                                } else {
                                    failed(new IOException(resStr));
                                }
                            }

                            @Override
                            public void failed(IOException e) {
                                Utils.SoutErr(e.getMessage());
                            }
                        });
                    }
                } else if (view1.getId() == R.id.replay_item_avatar) {
                    Intent intent = new Intent(ReplayActivity.this, OtherUserDetailActivity.class);
                    intent.putExtra("id", sonAdapter.getItem(position).getUseId());
                    startActivity(intent);
                }
            });


        }

        dialog.show();


    }

    private void showCommentDialog() {
        if (!Utils.isLogin()) {
            Utils.showToast("请先登录");
        } else {
            inputTextMsgDialog.show();
        }
    }

    /**
     * 初始化底部评论弹窗
     */
    private void initCommentDialog() {
        if(inputTextMsgDialog == null) {
            inputTextMsgDialog = new InputTextMsgDialog(this, R.style.dialog_center);
            inputTextMsgDialog.setmOnTextSendListener(new InputTextMsgDialog.OnTextSendListener() {
                @Override
                public void onTextSend(String msg) {
                    inputTextMsgDialog.dismiss();

                    loadingDialog.show();


                    Network.sendComments(
                            Utils.getUserId(),
                            replayType,
                            commendedId,
                            msg,
                            commentedUserId,
                            new HttpUtil.MyCallback() {
                                @Override
                                public void success(Response res) throws IOException {
                                    String resultStr = res.body().string();
                                    ResultBean resultBean = new Gson().fromJson(resultStr, ResultBean.class);
                                    if (resultBean.getCode().equals(200)) {
                                        loadingDialog.dismiss();
                                        pageInfo.reset();
                                        // 重新获取子评论
                                        mViewModel.loadSonComments(commendedId, pageInfo.getPage());

                                    } else {
                                        failed(new IOException(resultStr));
                                    }

                                }

                                @Override
                                public void failed(IOException e) {
                                    loadingDialog.dismiss();
                                    Utils.showToastSync("评论失败");
                                }
                            });


                }
            });
        }
    }

    /**
     * 子评论上拉加载更多
     */
    private void initSonLoadMore(int superId) {
        sonAdapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                sonRequest(superId);
            }
        });
        sonAdapter.getLoadMoreModule().setAutoLoadMore(true);
        //当自动加载开启，同时数据不满一屏时，是否继续执行自动加载更多(默认为true)
        sonAdapter.getLoadMoreModule().setEnableLoadMoreIfNotFullPage(false);
    }

    private void sonRequest(int superId) {
        mViewModel.loadSonComments(superId, pageInfo.getPage());
    }


    private void initRecycler() {

        // 侧滑监听
        OnItemSwipeListener onItemSwipeListener = new OnItemSwipeListener() {
            NoticeCommentBean commentBean = null;

            @Override
            public void onItemSwipeStart(RecyclerView.ViewHolder viewHolder, int pos) {
                commentBean = adapter.getItem(pos);
            }

            @Override
            public void clearView(RecyclerView.ViewHolder viewHolder, int pos) {
            }

            @Override
            public void onItemSwiped(RecyclerView.ViewHolder viewHolder, int pos) {
                Utils.Sout("View Swiped: " + pos);
                mViewModel.deleteItem(commentBean);
            }

            @Override
            public void onItemSwipeMoving(Canvas canvas, RecyclerView.ViewHolder viewHolder, float dX, float dY, boolean isCurrentlyActive) {
                canvas.drawColor(ContextCompat.getColor(ReplayActivity.this, R.color.zzl_red));
            }
        };

        adapter = new ReplayAdapter();
        binding.replayRecycler.setLayoutManager(new LinearLayoutManager(this));
        adapter.getDraggableModule().setSwipeEnabled(true);
        adapter.getDraggableModule().setOnItemSwipeListener(onItemSwipeListener);
        adapter.getDraggableModule().getItemTouchHelperCallback().setSwipeMoveFlags(ItemTouchHelper.START | ItemTouchHelper.END);
        binding.replayRecycler.setAdapter(adapter);
        adapter.setAnimationEnable(true);   // recyclerview加载动画
    }

    private void observer() {
        mViewModel.getNoticeCommentsLiveData().observe(this, noticeCommentBeans -> {
            adapter.setList(noticeCommentBeans);
        });

        mViewModel.getSuperCommentLiveData().observe(this, superCommentBean -> {
            if (superCommentBean != null) {
                ((TextView) sonCommentView.findViewById(R.id.replay_nums)).setText("回复");
                // 点击箭头关闭BottomSheetDialog
                ((ImageButton) sonCommentView.findViewById(R.id.replay_back_btn)).setOnClickListener(v -> dialog.cancel());

                ((TextView) sonCommentView.findViewById(R.id.comment_item_username)).setText(superCommentBean.getUserName());
                ((TextView) sonCommentView.findViewById(R.id.comment_item_time)).setText(
                        DateUtils.millis2String(Long.parseLong(superCommentBean.getCommentTime()), DateUtils.yyyyMMdd.get())
                );
                ((TextView) sonCommentView.findViewById(R.id.comment_item_text)).setText(superCommentBean.getCommentText());
                ((TextView) sonCommentView.findViewById(R.id.comment_item_go_replay)).setVisibility(View.GONE);
                //((TextView) sonCommentView.findViewById(R.id.comment_item_like_nums)).setText(String.valueOf(superCommentBean.getCommentLikes()));
                ((TextView) sonCommentView.findViewById(R.id.comment_item_like_nums)).setVisibility(View.INVISIBLE);
                sonCommentView.findViewById(R.id.comment_item_like_btn).setVisibility(View.INVISIBLE);
                Glide.with(this)
                        .load(superCommentBean.getImgUrl())
                        .into((ImageView)sonCommentView.findViewById(R.id.comment_item_avatar));

                TextView goDetailPage = sonCommentView.findViewById(R.id.go_detail_page);
                goDetailPage.setVisibility(View.VISIBLE);
                goDetailPage.setOnClickListener(v -> {

                    Intent intent = null;
                    if (superCommentBean.getType().equals(ReplayType.BASE)) {
                        intent = new Intent(ReplayActivity.this, BaseDetailActivity.class);
                        intent.putExtra("id", superCommentBean.getTo_id());
                        intent.putExtra("is_comment", true);
                    } else if (superCommentBean.getType().equals(ReplayType.DYNAMIC)) {
                        intent = new Intent(ReplayActivity.this, DynamicDetailActivity.class);
                        intent.putExtra("id", superCommentBean.getTo_id());
                        intent.putExtra("is_comment", true);
                    } else if (superCommentBean.getType().equals(ReplayType.TRAVEL)) {
                        intent = new Intent(ReplayActivity.this, TravelDetailActivity.class);
                        intent.putExtra("travel_id", superCommentBean.getTo_id());
                        intent.putExtra("is_comment", true);
                    }
                    if (intent != null) {
                        startActivity(intent);
                    }


                });

                // 点击子评论弹出评论框
                initSonLoadMore(superCommentBean.getCommentId());
            }
        });

        mViewModel.getSonCommentsLiveData().observe(this, sonCommentBeans -> {

            if(sonCommentBeans != null) {

                if (pageInfo.isFirstPage()) {
                    sonAdapter.setList(sonCommentBeans);
                } else {
                    sonAdapter.addData(sonCommentBeans);
                }
                pageInfo.nextPage();
                // 加载完成，等待下一次加载
                sonAdapter.getLoadMoreModule().loadMoreComplete();
            }

        });

    }

    @Override
    protected void onResume() {
        super.onResume();

        if (!Utils.isLogin()) {
            Utils.showToast("请先登录");
            //Utils.goLogin(this);
        } else {
            mViewModel.loadNoticeComments(Utils.getUserId());
        }

    }
}